<?php
/*
* StiPHPcms, A web Content management System made with PHP/MySQL
* JordSti : jord52@gmail.com
* Version : 0.0.2
*
* Copyright (C) 2009  jord52@gmail.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

class Module {
	private $cms;
	
	public $name;
	public $version;
	public $author;

	public function __construct($cms)
	{
		$this->name = "WoW Armory (STI)";
		$this->version = "0.0.1";
		$this->author= "StiTeam";
		
		$this->cms = $cms;
	}
	
	public function getLang($key)
	{
		return $this->cms->lang[$key];
	}
	
	public function run()
	{
		if(isset($_GET['a']))
		{
			$action = $_GET['a'];
		}
		else
		{
			$action = 'memberslist';
		}
		
		if($action=='install')
		{
			$this->install();
		}
		else if($action=='parsearmoryxml')
		{
			$this->parseArmoryXml();
		}
		else if($action=='memberslist')
		{
			$this->membersList();
		}
		else if($action=='linkchar')
		{
			$this->linkCharacter();
		}
		else if($action=='linkchartoaccount')
		{
			$this->LinkCharToAccount();
		}
		else if($action=='dropchar')
		{
			$this->DropLinkedChar();
		}
		
	}
	
	private function NeedMemberRank()
	{
		if($this->cms->getUserRank()<$this->cms->settings['wow_memberrank'])
		{
			$this->cms->error($this->getLang('right_error'));
		}
	}
	
	private function DropLinkedChar()
	{
		$this->NeedMemberRank();
		
		$mem_id = intval($_GET['mid']);
		$user_id = $_SESSION['user_id'];
		
		$dt = $this->cms->sql_query("SELECT * FROM %prefix%members WHERE id=$mem_id");
		
		$data = mysql_fetch_array($dt);
		
		if($data['uid']==$user_id)
		{
			$this->cms->sql_query("UPDATE %prefix%members SET uid=0 WHERE id=$mem_id");
		}
		else
		{
			$this->cms->error($this->getLang('wow_charnotlinkedtoaccount'));
		}
		
		$this->linkCharacter();
	}
	
	public function linkCharacter()
	{
		$this->NeedMemberRank();
		
		$user_id = $_SESSION['user_id'];
		
		$dt = $this->cms->sql_query("SELECT * FROM %prefix%members WHERE uid=$user_id");
		
		$nb_char = mysql_num_rows($dt);
		
		$html = '<p>'.str_replace('%nb',$nb_char,$this->getLang('wow_nblinkedchar')).'</p>';
		
		if($nb_char!=0)
		{
		
		$html .= $this->CharTableHeader(true);
		$i = 0;
		
			while($data = mysql_fetch_array($dt))
			{
				if($i==0)
				{
					$rowclass = "row01";
					$i = 1;
				}
				else
				{
					$rowclass = "row02";
					$i = 0;
				}
			
				$toon = new WowToon($data);
				$html .= $this->CharRow($rowclass,$toon,true);
			}
		
			$html .= '</table>';
		}
		
		$dt = $this->cms->sql_query("SELECT * FROM %prefix%members WHERE uid=0");
		while($data = mysql_fetch_array($dt))
		{
			$id = $data['id'];
			$charList[$id] = $data['cname'];
		}
		$this->cms->renderHeader($this->getLang("wow_members_list"));
		$this->cms->renderMenu();
		$this->cms->template->addFrame("",$html);
		$this->cms->template->addFrame("",$this->LinkCharForm($charList));
	}
	
	private function LinkCharToAccount()
	{
		$this->NeedMemberRank();
		
		$user_id = $_SESSION['user_id'];
		$mem_id = intval($_POST['chartolink']);
		
		$dt = $this->cms->sql_query("SELECT * FROM %prefix%members WHERE id=$mem_id");
		
		$data = mysql_fetch_array($dt);
		
		if($data['uid']!=0)
		{
			$this->cms->error($this->getLang('wow_charalreadylinked'));
		}
		
		$this->cms->sql_query("UPDATE %prefix%members SET uid=$user_id WHERE id=$mem_id");
		
		$this->linkCharacter();
	}
	
	private function LinkCharForm($CharList)
	{
		$html = '<form method="post" action="mod.php?mod=wowarmory&a=linkchartoaccount">';
		
		$html .= '<p><label for="chartolink">'.$this->getLang('wow_char_name').' : </label><select name="chartolink" id="chartolink">';
		
		foreach($CharList as $id => $name)
		{
			$html .= '<option value="'.$id.'">'.$name.'</option>';
		}
		
		$html .= '</select></p>';
		
		$html .= '<p><input type="submit" value="'.$this->getLang('wow_linkbutton').'"/></p></form>';

		return $html;
	}
	
	private function MemberBar()
	{
		if($this->cms->getUserRank()>=$this->cms->settings['wow_memberrank'])
		{
			$this->cms->template->addHTML('<p><a href="mod.php?mod=wowarmory&a=linkchar">'.$this->getLang('wow_linkchar').'</a></p><p><a href="mod.php?mod=wowarmory&a=parsearmoryxml">'.$this->getLang('wow_updatearmory').'</a></p>');
		}
	}
	
	private function CharTableHeader($char_link = false)
	{
		if($char_link)
		{
			return '<table align="center" width="80%" border="0" cellpadding="0" cellspacing="0">
            <tr class="rowhead"><td width="24%">'.$this->getLang("wow_char_name").'</td>
              <td width="10%">'.$this->getLang("wow_level").'</td>
              <td width="20%">'.$this->getLang("wow_achievement_point").'</td>
              <td width="16%">&nbsp;</td>
              <td width="18%">'.$this->getLang("wow_rank").'</td>
              <td width="18%">-</td>
            </tr>';
		}
		else
		{
			return '<table align="center" width="80%" border="0" cellpadding="0" cellspacing="0">
            <tr class="rowhead"><td width="24%">'.$this->getLang("wow_char_name").'</td>
              <td width="10%">'.$this->getLang("wow_level").'</td>
              <td width="20%">'.$this->getLang("wow_achievement_point").'</td>
              <td width="16%">&nbsp;</td>
              <td width="18%">'.$this->getLang("wow_rank").'</td>
            </tr>';
		}
	}
	
	private function CharRow($rowclass,$toon,$char_link = false)
	{
		if($char_link)
		{
			return '<tr class="'.$rowclass.'">
              	<td><a href="'.$toon->getArmoryUrl($this->cms->settings['wow_realm']).'" target="_blank">'.$toon->cname.'</a></td>
              	<td>'.$toon->lvl.'</td>
              	<td>'.$toon->achpoints.'</td>
              	<td><img src="'.$toon->getRaceIcon().'"><img src="'.$toon->getClassIcon().'" width="18" height="18"></td>
              	<td>'.$toon->rank.'</td>
              	<td><a href="mod.php?mod=wowarmory&a=dropchar&mid='.$toon->id.'">'.$this->getLang('delete').'</a></td>
            	</tr>';
		}
		else
		{
			return '<tr class="'.$rowclass.'">
              	<td><a href="'.$toon->getArmoryUrl($this->cms->settings['wow_realm']).'" target="_blank">'.$toon->cname.'</a></td>
              	<td>'.$toon->lvl.'</td>
              	<td>'.$toon->achpoints.'</td>
              	<td><img src="'.$toon->getRaceIcon().'"><img src="'.$toon->getClassIcon().'" width="18" height="18"></td>
              	<td>'.$toon->rank.'</td>
            	</tr>';
		}
	}
	
	public function membersList()
	{
		
		$html = $this->CharTableHeader();
		
		
		$dt = $this->cms->sql_query("SELECT * FROM %prefix%members ORDER BY rank");
		$i = 0;
		while($data=mysql_fetch_array($dt))
		{
			if($i==0)
			{
				$rowclass = "row01";
				$i = 1;
			}
			else
			{
				$rowclass = "row02";
				$i = 0;
			}
			
			$toon = new WowToon($data);
			$html .= $this->CharRow($rowclass,$toon);
		}
		
		$html .= '</table>';
		
		$this->cms->renderHeader($this->getLang("wow_members_list"));
		$this->cms->renderMenu();
		$this->MemberBar();
		$this->cms->template->addFrame("",$html);
		
	}
	
	public function parseArmoryXml()
	{
		
		$RaceArray = array(
			1 => 'Human',
			2 => 'Orc',
			3 => 'Dwarf',
			4 => 'Night Elf',
			5 => 'Undead',
			6 => 'Tauren',
			7 => 'Gnome',
			8 => 'Troll',
			10 => 'Blood Elf',
			11 => 'Draenei');
			
		$ClassArray = array(
			1 => 'Warrior',
			2 => 'Paladin',
			3 => 'Hunter',
			4 => 'Rogue',
			5 => 'Priest',
			6 => 'Death Knight',
			7 => 'Shaman',
			8 => 'Mage',
			9 => 'Warlock',
			11 => 'Druid ');
	
		
		//$guild_name = $config->guild_name;
		//$realm = $config->realm;
		$fp = fopen('cache/armory.xml','r');
		$filebuff = "";
		while($data = fgets($fp))
		{
			$filebuff .= $data;
		}

		fclose($fp);


		preg_match_all('#<character achPoints="([0-9]+)" classId="([0-9]+)" genderId="([0-9]+)" level="([0-9]+)" name="(.+)" raceId="([0-9]+)" rank="([0-9]+)" url="(.+)"/>#isU',$filebuff,$matches);
	
		/*
	 	* Achievement -> 1
	 	* ClassId -> 2
	 	* GenderId -> 3
	 	* Level -> 4
	 	* Name -> 5
	 	* RaceId -> 6
	 	* Rank -> 7
	 	*/
		$nbPlayer = 0;
	
		foreach($matches[0] as $var1)
		{
		$nbPlayer++;
		}

		$dt = $this->cms->sql_query("SELECT * FROM %prefix%members");
		
		$char_in_db = array();
		
		while($data=mysql_fetch_array($dt))
		{
			$id = $data['id'];
			$char_in_db[$id] = $data['cname'];
		}
		
		for($i=0; $i<$nbPlayer; $i++)
		{

			$cname = $matches[5][$i];
			$lvl = $matches[4][$i];
			$sex = $matches[3][$i];
			$race = $matches[6][$i];
			$class = $matches[2][$i];
			$achpoints = $matches[1][$i];
			$rank = $matches[7][$i];
			$stamp = time();
			
			$race = $RaceArray[$race];
			$class = $ClassArray[$class];
			
			if($this->PlayerPresentInLastUpdate($cname,$matches[5]))
			{
				$CharId = $this->SearchPlayer($cname,$char_in_db);
				
				if($CharId==-1)
				{
					echo 'Insert '.$cname.'<br>';
					$this->cms->sql_query("INSERT INTO %prefix%members VALUES('','$cname',$lvl,$achpoints,'$class',$sex,'$race','$rank','',$stamp)");
				}
				else
				{
					echo 'Updating '.$cname.'<br>';
					$this->cms->sql_query("UPDATE %prefix%members SET cname='$cname',lvl='$lvl',achpoints='$achpoints',rank='$rank',lastup='$stamp' WHERE id=$CharId");
				}
			}
		}
		
		foreach($char_in_db as $id => $name)
		{
			if(!$this->PlayerPresentInLastUpdate($name,$matches[5]))
			{
				$CharId = $this->SearchPlayer($name,$char_in_db);
				
				if($CharId!=-1)
				{
					echo 'Deleting '.$name.'<br>';
					$this->cms->sql_query("DELETE FROM %prefix%members WHERE id=$CharId");
				}
			}
		}
	}
	
	private function PlayerPresentInLastUpdate($CharName,$ArmoryCharArray)
	{
		$isPresent = false;
		
		foreach($ArmoryCharArray as $id => $name)
		{
			if($CharName==$name)
			{
				$isPresent = true;
			}
		}
		
		return $isPresent;
	}
	
	private function SearchPlayer($CharName,$char_array)
	{
		$CharId = -1;
		
		foreach($char_array as $id => $name)
		{
			if($name==$CharName)
			{
				$CharId = $id;
			}
		}
		
		return $CharId;
	}
	
	public function install()
	{
		/*
		 * 
		 * 
		 * 	'wow_class' => 'Classe',
			'wow_level' => 'Lvl',
			'wow_char_name' => 'Nom',
			'wow_achievement_point' => 'Achievements',
			'wow_race' => 'Race',
			'wow_gender' => 'Sexe',
		 	'wow_members_list' => 'Les Membres',
		 	'wow_rank' => 'Rang',
		  	'wow_linkchar'
			'wow_nblinkedchar'
			'wow_linkbutton'
			'wow_charalreadylinked'
			'wow_charnotlinkedtoaccount'
		 */
		$this->cms->addSetting('wow_guildname','MyfckGuild'); 
		$this->cms->addSetting('wow_realm','myrealm'); 
		$this->cms->addSetting('wow_rankadmin',32); 
		$this->cms->addSetting('wow_memberrank',2);
		
		$this->cms->sql_query("CREATE TABLE IF NOT EXISTS `%prefix%members` (
		`id` int(255) NOT NULL AUTO_INCREMENT,
  		`cname` varchar(64) NOT NULL,
  		`lvl` int(255) NOT NULL,
  		`achpoints` int(255) NOT NULL,
  		`class` varchar(32) NOT NULL,
  		`sex` int(2) NOT NULL,
  		`race` varchar(32) NOT NULL,
  		`rank` int(255) NOT NULL,
  		`uid` int(25) NOT NULL,
  		`lastup` int(32) NOT NULL,
  		PRIMARY KEY (`id`)) ENGINE=InnoDB  DEFAULT CHARSET=latin1;");
		
	}
	
	
}

class WowToon{
	public $lvl;
	public $cname;
	public $achpoints;
	public $rank;
	public $pclass;
	public $race;
	public $sex;
	public $id;
	public $uid;

	public function __construct($data)
	{
		$this->lvl = $data['lvl'];
		$this->cname = $data['cname'];
		$this->achpoints = $data['achpoints'];
		$this->rank = $data['rank'];
		$this->pclass = $data['class'];
		$this->race = $data['race'];
		$this->sex = $data['sex'];
		$this->id = $data['id'];
		$this->uid = $data['uid'];
	}

	public function getArmoryUrl($guild_name)
	{
		$url = 'http://www.wowarmory.com/character-sheet.xml?r='.str_replace(' ','+',$guild_name).'&n='.$this->cname;
		return $url;
	}
	
	public function getRaceIcon()
	{
		$imgurl = 'images/wowarmory/race/'.strtolower(str_replace(' ','',$this->race));
		if($this->sex == 0)
		{
			$imgurl .= '_m';
		}
		else
		{
			$imgurl .= '_f';
		}

		$imgurl .= '.gif';
		return $imgurl;
	}

	public function getClassIcon()
	{
		$imgclass = 'images/wowarmory/class/'.strtolower(str_replace(' ','',$this->pclass)).'.png';
		return $imgclass;
	}

}
	
?>